package com.bilin.coin.common.base;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.bilin.coin.R;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.callback.StringCallBack;
import com.bilin.coin.utils.DialogUtils;
import com.bilin.coin.utils.FilePathUtils;
import com.bilin.coin.utils.MPermissionUtils;
import com.bilin.coin.widget.CustomPopupWindow;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import id.zelory.compressor.Compressor;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


public abstract class UploadImgActivity extends BaseAppCompatActivity {

    protected CustomPopupWindow popupWindow;
    //相机回调requestCode
    private static final int CAMERA_PHOTO = 0x1911;
    //裁剪去
    private static final int REQUEST_CROP_PHOTO = 0x1920;
    //裁剪返回
    public static final int RESULT_CROP_PHOTO = 0x1921;
    //图库返回回调
    public static final int RESULT_CODE_POPTH = 0x1455;

    //拍照图片地址
    private String strImgPath;
    protected String backImgUrl;//上传成功服务器返回的地址
    private int selecttype;//0拍照 1相册


    @Override
    protected void initData() {
        initPop();
    }

    private void initPop() {
        popupWindow = new CustomPopupWindow.Builder()
                .setContext(this)
                .setContentView(R.layout.pw_photo_select)
                .setwidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setheight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setFouse(true)  //是否可以获取焦点
                .setOutSideCancel(true) //设置点击外部取消
                .setAnimationStyle(R.style.PopupWindowAnim)
                //.setBackGroudAlpha(mActivity,0.7f) //是否设置背景色，原理为调节 alpha
                .builder();//

        TextView pz = (TextView) popupWindow.getItemView(R.id.tv_Photograph);
        TextView xc = (TextView) popupWindow.getItemView(R.id.tv_Album);
        TextView qx = (TextView) popupWindow.getItemView(R.id.tv_cancel);

        xc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selecttype = 1;
                CheckPermissions();
                popupWindow.dismiss();
            }
        });

        pz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selecttype = 0;
                CheckPermissions();
                popupWindow.dismiss();
            }
        });

        qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                backgroundAlpha(1.0f);
            }
        });
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    /**
     * 检查权限
     */
    private void CheckPermissions() {
        String permission[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA};
        MPermissionUtils.requestPermissionsResult(this, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                if (selecttype == 0) {
                    showCamera();
                } else if (selecttype == 1) {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, RESULT_CODE_POPTH);
                }
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(UploadImgActivity.this);
            }
        }, permission);
    }

    /**
     * 打开相机
     */
    public void showCamera() {
        Intent itCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //生成图片地址
        File file = FilePathUtils.accessPath(this, "picture");
        strImgPath = FilePathUtils.getFileName(file, "IMG_" + System.currentTimeMillis() + ".jpg");
        File pathFile = new File(strImgPath);
        //兼容7.0权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            itCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //通过FileProvider创建一个content类型的Uri
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, pathFile.getAbsolutePath());
            Uri uri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            itCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            Uri uri = Uri.fromFile(pathFile);
            itCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        try {
            this.startActivityForResult(itCamera, CAMERA_PHOTO);
        } catch (ActivityNotFoundException anf) {
            this.showToast("The camera is not ready");
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            //获取图片地址
            case CAMERA_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (!TextUtils.isEmpty(strImgPath)) {
                        Compressor(strImgPath);
                    }
                }
                break;
            //从图库中选择回调
            case RESULT_CODE_POPTH:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        Compressor(getRealFilePath(UploadImgActivity.this, uri));
                    }
                }
                break;
        }
    }

    //压缩图片文件
    private void Compressor(String url) {
        new Compressor(this)
                .compressToFileAsFlowable(new File(url))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) {
                        if (file != null) {
                            DialogUtils.showDialogLoading(UploadImgActivity.this);
                            goFile(file);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                        showToast(throwable.getMessage());
                    }
                });
    }

    /**
     * 上传图片文件
     *
     * @param file
     */
    private void goFile(File file) {
        RequestUtils
                .getUpDateFile2()///v1/account/cclog/upload
                .url(fillUrl())
                .addFileParams(file)
                //.addParams("type", "1")
                .build()
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new StringCallBack<String>() {
                    @Override
                    public void onCallBackNext(String result) {
                        DialogUtils.dismissDialogLoading();
                        try {
                            JSONObject dataJson = new JSONObject(result);
                            //backImgUrl = GdproApplication.strImageUrl + "/" + dataJson.getString("data");
                            backImgUrl = dataJson.getString("data");
                            if (!isDestroyed())
                                childDoWork(backImgUrl);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCallBackError(Throwable e) {
                     /*   code: 1 图片不存在
                        2 图片大小不能大于3M
                        3 无效的图片
                        4|5 网络错误*/
                        if (!isDestroyed())
                            childDoWork("");
                        showMsg(e);
                    }
                });
    }

    protected abstract String fillUrl(); /*{
        return "/api/v1/account/cclog/upload";
    }*/

    protected void childDoWork(String backImgUrl) {

    }

    /**
     * 图片绝对地址转换成相对地址
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
}
